package com.iot.platform.mvc.device.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.iot.common.core.exception.ModelException;
import com.iot.common.core.util.R;
import com.iot.common.security.annotation.SecurityAuthorization;
import com.iot.platform.api.domain.DeviceGroup;
import com.iot.platform.api.domain.DeviceGroupRelation;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.Setter;

@RestController
@RequiredArgsConstructor
@RequestMapping("/device/group/relation")
@Api(value = " DeviceGroup", tags = "产品方法")
public class DeviceGroupRelationController {

	@Setter
	private Throwable cause;

	@SecurityAuthorization
	@GetMapping(value = { "/list" }, produces = "application/json; charset=utf-8")
	public R<List<DeviceGroup>> list(
			@RequestParam(name = "deviceId", required = false, defaultValue = "") String deviceId) throws Exception {
		return R.ok(DeviceGroup.dao.find("select a.name,a.id,b.create_time from " + DeviceGroup.TABLE_NAME + " a,"
				+ DeviceGroupRelation.TABLE_NAME + " b where a.id=b.group_id and device_id=? ", deviceId));
	}

	@SecurityAuthorization
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public R<DeviceGroupRelation> save(@Valid DeviceGroupRelation relation) {
		if (relation == null) {
			throw new ModelException("对象不可以为空！");
		}
		DeviceGroupRelation groupRelation = DeviceGroupRelation.dao.findByIds(relation.getGroupId(),
				relation.getDeviceId());
		if (groupRelation != null) {
			return R.failed("设备已在改分组，无需重复分配！");
		}

		if (relation.save()) {
			return R.ok(relation);
		}
		return R.failed();
	}

	@SecurityAuthorization
	@GetMapping(value = { "/deleteById" }, produces = "application/json; charset=utf-8")
	public R<Boolean> deleteById(@RequestParam(name = "id", required = true) String id) throws Exception {
		if (DeviceGroupRelation.dao.deleteById(id)) {
			return R.ok(true);
		} else {
			return R.failed(false);
		}
	}

}
